package com.wanew.activity;

import java.util.HashMap;

import net.sourceforge.simcpux.Util;

import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.reyun.sdk.ReYunTrack;
import com.wan.activity.BaseActivity;
import com.wan.activity.WanPhoneRegesterActivity;
import com.wan.activity.forgetPasswordActivity;
import com.wan.commonsdk.Conet;
import com.wan.commonsdk.HttpUtils;
import com.wan.commonsdk.WanCommonSdk;
import com.wan.commonsdk.WanServerResposeCode;

public class WANLoginDialogActivity extends BaseActivity implements
		OnClickListener {

	private Button wan51_dialog_login_btn, wan51_dialog_regbtn;
	private LinearLayout wan51_login_linear, wan51_reg_include;

	private ImageView wan51_login_imgb, wan51_reg_imgb;

	private final int LOGIN_SUCCESS = 1;
	private final int LOGIN_FAILE = -1;
	private final int REG_SUCCESS = 2;
	private final int REG_FAIL = -2;
	private final int NETWORK_ERROR = 10086;
	private Thread login_mThread = null;
	private Thread reg_mThread = null;

	private String status, commend;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case LOGIN_SUCCESS:
				hideLoading();
				/*
				 * ReYunTrack.setRegisterWithAccountID(Conet.mUserInfo
				 * .getUser_id());
				 */
				ReYunTrack
						.setLoginSuccessBusiness(Conet.mUserInfo.getUser_id());
				// finish();
				WanCommonSdk.loginCallBack.loginSuccess(
						Conet.mUserInfo.getUser_id(),
						Conet.mUserInfo.getAccess_token());
				
				Editor edit = Conet.WANSP.edit();
				edit.putString("wanname", Conet.mUserInfo.getUser_name());
				edit.putString("wanpasswod", Conet.mUserInfo.getUser_password());
				edit.commit();
				Conet.getInstance().exit();
				finish();
				// 返回登陆成功 函数
				break;
			case LOGIN_FAILE:
				hideLoading();
				showHint(getString(Util.getResID("login_error_hint", "string")));
				login_mThread = null;
				break;
			}
			;
		}
	};

	private Handler regHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case 0:

				hideLoading();
				// 注册成功的回调

				/*
				 * TrackingIO.setRegisterWithAccountID(Conet.mUserInfo.getUser_id
				 * ());
				 * 
				 * 
				 * TrackingIO.setLoginSuccessBusiness(Conet.mUserInfo.getUser_id(
				 * ));
				 */

				ReYunTrack
						.setLoginSuccessBusiness(Conet.mUserInfo.getUser_id());
				ReYunTrack.setRegisterWithAccountID(Conet.mUserInfo
						.getUser_id());
				WanCommonSdk.loginCallBack.loginSuccess(
						Conet.mUserInfo.getUser_id(),
						Conet.mUserInfo.getAccess_token());
				
				Editor edit = Conet.WANSP.edit();
				edit.putString("wanname", Conet.mUserInfo.getUser_name());
				edit.putString("wanpasswod", Conet.mUserInfo.getUser_password());
				edit.commit();
				
				Conet.getInstance().exit();
				finish();

				break;

			case -1:
				hideLoading();
				showHint(getString(Util.getResID("login_error_hint", "string")));
				reg_mThread = null;
				break;
			case WanServerResposeCode.WAN_REGESTER_WRONG_USERNAME:
				hideLoading();
				showHint("用户名已被使用");
				reg_mThread = null;
				break;
			case WanServerResposeCode.WAN_REGESTER_WRONG_PASSWORD:
				hideLoading();
				showHint(getString(Util.getResID("reg_password_hint", "string")));
				reg_mThread = null;
				break;
			case WanServerResposeCode.WAN_HAS_ACCOUNT:
				hideLoading();
				Toast.makeText(getApplicationContext(), "用户名已注册", Toast.LENGTH_SHORT).show();
				break;
			case NETWORK_ERROR:
				hideLoading();
				showHint(getString(Util.getResID("newwork_error", "string")));
				reg_mThread = null;
				break;
			default:
				hideLoading();
				showToast(status);
				reg_mThread = null;
				break;
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(Util.getResID("wan51_main_dialog_activity", "layout"));
		Conet.getInstance().addActivity(this);
		wan51_dialog_login_btn = (Button) findViewById(Util.getResID("wan51_dialog_login_btn", "id"));
		
		wan51_dialog_regbtn = (Button) findViewById(Util.getResID("wan51_dialog_regbtn", "id"));

		wan51_login_linear = (LinearLayout) findViewById(Util.getResID("wan51_login_linear","id"));
		wan51_reg_include = (LinearLayout) findViewById(Util.getResID("wan51_reg_include","id"));

		wan51_login_imgb = (ImageView) findViewById(Util.getResID("wan51_login_imgb","id"));
		wan51_reg_imgb = (ImageView) findViewById(Util.getResID("wan51_reg_imgb","id"));
		loginInit();
		
	}

	public void wan_title_onclick(View v) {
		if (v.getId() == Util.getResID("wan51_dialog_login_btn","id")) {
			loginInit();
		} else if (v.getId() == Util.getResID("wan51_dialog_regbtn","id")) {
			registerInit();
		}
	}

	private void loginInit() {
		wan51_login_linear.setVisibility(View.VISIBLE);
		wan51_reg_include.setVisibility(View.GONE);
		wan51_dialog_login_btn.setTextColor(Color.rgb(41, 157, 242));
		wan51_dialog_regbtn.setTextColor(Color.rgb(148, 148, 148));

		wan51_login_imgb.setBackgroundColor(Color.rgb(41, 157, 242));
		wan51_reg_imgb.setBackgroundColor(Color.rgb(148, 148, 148));

		findViewById(Util.getResID("wan51_loginbtn","id")).setOnClickListener(this);// 登录按钮 设置监听
		findViewById(Util.getResID("wan51_findpw_btn","id")).setOnClickListener(this);// 找回密码 
		
		
		String wanname = Conet.WANSP.getString("wanname", null);
		String pw = Conet.WANSP.getString("wanpasswod", null);
		
		EditText unameEdit = (EditText) findViewById(Util.getResID("wan51_login_uname_edit", "id"));
		EditText pwEdit = (EditText) findViewById(Util.getResID("wan51_loginpw_edit", "id"));
		unameEdit.setText(wanname);
		pwEdit.setText(pw);
		
	};
	private void registerInit() {
		wan51_login_linear.setVisibility(View.GONE);
		wan51_reg_include.setVisibility(View.VISIBLE);
		wan51_dialog_login_btn.setTextColor(Color.rgb(148, 148, 148));
		wan51_dialog_regbtn.setTextColor(Color.rgb(41, 157, 242));

		wan51_login_imgb.setBackgroundColor(Color.rgb(148, 148, 148));
		wan51_reg_imgb.setBackgroundColor(Color.rgb(41, 157, 242));

		findViewById(Util.getResID("wan51_regbtn","id")).setOnClickListener(this);
		findViewById(Util.getResID("wan51_phoneregbtn","id")).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() ==  Util.getResID("wan51_loginbtn","id")){// 登录
			showLoading("登录中。。。");
			EditText uname_edit = (EditText) findViewById(Util.getResID("wan51_login_uname_edit","id"));
			final String username = uname_edit.getText().toString().trim();// 获取帐号

			EditText pw_edit = (EditText) findViewById(Util.getResID("wan51_loginpw_edit","id"));
			final String password = pw_edit.getText().toString().trim(); // 获取
			if (!checkUserInfo(username, password)) {
				return;
			}	
			Conet.mUserInfo.setUser_name(username);
			Conet.mUserInfo.setUser_password(password);// 密码
			login_mThread = new Thread(new Runnable() {// 异步访问登录请求

						@Override
						public void run() {
							// TODO Auto-generated method stub
							login(username, password);
						}
					});
			login_mThread.start();
		}else if(v.getId() == Util.getResID("wan51_regbtn","id")){
			EditText uname_ed = (EditText) findViewById(Util.getResID("wan51_regname_edit","id"));
			final String uname = uname_ed.getText().toString().trim();// 获取帐号
			EditText pw_ed = (EditText) findViewById(Util.getResID("wan51_regpw_edit","id"));
			final String psword = pw_ed.getText().toString().trim(); // 获取
		
			if (!checkUserInfo(uname, psword)) {
				return;
			}
			Conet.mUserInfo.setUser_name(uname);
			Conet.mUserInfo.setUser_password(psword);// 密码
			reg_mThread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					regzc(uname, psword);
				}
			});
			
			reg_mThread.start();
		}else if(v.getId() == Util.getResID("wan51_findpw_btn","id")){
			Intent intent = new Intent(this, forgetPasswordActivity.class);
			this.startActivity(intent);
		}else if(v.getId()  == Util.getResID("wan51_phoneregbtn","id")){
			Intent phoneintent = new Intent(this,WanPhoneRegesterActivity.class);
			this.startActivity(phoneintent);
		}
	}

	private void login(String username, String password) {
	
		HashMap<String, String> result = null;
		result = HttpUtils.HttpLogin(username, password);
		Conet.mUserInfo.setUser_name(username);
		Conet.mUserInfo.setUser_password(password);
		Conet.mUserInfo.setGuest(false);

		if (result == null) {
			mHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
		} else {
			if (result.get("status").equals("0")) {
				Conet.mUserInfo.setUser_id(result.get("user_id"));
				Conet.mUserInfo.setAccess_token(result.get("access_token"));
				mHandler.obtainMessage(LOGIN_SUCCESS, Conet.mUserInfo)
						.sendToTarget();
			} else {
				mHandler.obtainMessage(LOGIN_FAILE, Conet.mUserInfo)
						.sendToTarget();
			}
		}
	}

	private void regzc(String username, String password) {
		

		HashMap<String, String> result = HttpUtils.HttpReg(username, password);
		
		
		
		
		if (result == null) {
			mHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
			return;
		} else if (result.get("status").equals(
				String.valueOf(WanServerResposeCode.WAN_REGESTER_SUCCESS))) {
			// UserInfo userInfo = new UserInfo();
			Conet.mUserInfo.setUser_name(username);
			Conet.mUserInfo.setUser_password(password);
			Conet.mUserInfo.setUser_id(result.get("user_id"));
			Conet.mUserInfo.setAccess_token(result.get("access_token"));

			Conet.mUserInfo.setGuest(false);
			regHandler.obtainMessage(WanServerResposeCode.WAN_REGESTER_SUCCESS,
					Conet.mUserInfo).sendToTarget();

			return;
		} else if (result.get("status").equals(
				String.valueOf(WanServerResposeCode.WAN_HAS_ACCOUNT))) {
			commend = result.get("commend");
		}
		status = result.get("status").toString();
		regHandler.obtainMessage(Integer.parseInt(result.get("status")))
				.sendToTarget();

	}

	private Boolean checkUserInfo(String uname, String upassword) {
		int un_length = uname.length();
		int pw_length = upassword.length();

		if (un_length == 0) {
			showHint(this.getString(Util.getResID("username_empty_hint",
					"string")));
			return false;
		}
		if (pw_length == 0) {
			showHint(this.getString(Util.getResID("password_empty_hint",
					"string")));
			return false;
		}
		if (un_length < WanCommonSdk.MIN_USERNAME_LENGTH
				|| un_length > WanCommonSdk.MAX_USERNAME_LENGTH) {
			showHint(this.getString(Util.getResID("username_length_hint",
					"string")));
			return false;
		}
		if (pw_length < WanCommonSdk.MIN_PASSWORD_LENGTH
				|| pw_length > WanCommonSdk.MAX_PASSWORD_LENGTH) {
			showHint(this.getString(Util.getResID("password_length_hint",
					"string")));

			return false;
		}
		return true;
	}

}
